# -*- coding: utf-8 -*-

#Author: Yuanhao Li <jay_21cn@hotmail.com>
#File: logindialog.py
#Usage: Client of ING from project Babel
#Copyright (C) 2007 Yuanhao Li<jay_21cn@hotmail.com>

#This program is free software; you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation; either version 2 of the License, or
#(at your option) any later version.

#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#GNU General Public License for more details.

#You should have received a copy of the GNU General Public License
#along with this program; if not, write to the Free Software Foundation,
#Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

#本程序是遵从 GPL 2.0 许可发布的. 你可以自由修改和再发布本程序, 
#但请遵守 GPL 2.0 条款, 尊重知识产权.

import sys, os, base64

from PyQt4 import QtCore, QtGui
from PyQt4.QtCore import Qt, QRegExp, QString

cwd = os.path.split(sys.argv[0])[0]
if not cwd:
	cwd = os.getcwd()

class Ui_Dialog(object):
    def setupUi(self, Dialog):
        Dialog.setObjectName("Dialog")
        Dialog.resize(QtCore.QSize(QtCore.QRect(0,0,303,248).size()).expandedTo(Dialog.minimumSizeHint()))
        Dialog.setWindowIcon(QtGui.QIcon(cwd + "/pixmaps/ingc.png"))

        self.layoutWidget = QtGui.QWidget(Dialog)
        self.layoutWidget.setGeometry(QtCore.QRect(10,12,282,210))
        self.layoutWidget.setObjectName("layoutWidget")

        self.vboxlayout = QtGui.QVBoxLayout(self.layoutWidget)
        self.vboxlayout.setMargin(0)
        self.vboxlayout.setSpacing(6)
        self.vboxlayout.setObjectName("vboxlayout")

        self.hboxlayout = QtGui.QHBoxLayout()
        self.hboxlayout.setMargin(0)
        self.hboxlayout.setSpacing(6)
        self.hboxlayout.setObjectName("hboxlayout")

        self.label = QtGui.QLabel(self.layoutWidget)
        self.label.setObjectName("label")
        self.label.setFixedWidth(80)
        self.hboxlayout.addWidget(self.label)

        self.loginName = QtGui.QLineEdit(self.layoutWidget)
        self.loginName.setObjectName("loginName")
        self.hboxlayout.addWidget(self.loginName)
        self.vboxlayout.addLayout(self.hboxlayout)

        self.hboxlayout1 = QtGui.QHBoxLayout()
        self.hboxlayout1.setMargin(0)
        self.hboxlayout1.setSpacing(6)
        self.hboxlayout1.setObjectName("hboxlayout1")

        self.label_2 = QtGui.QLabel(self.layoutWidget)
        self.label_2.setObjectName("label_2")
        self.label_2.setFixedWidth(80)
        self.hboxlayout1.addWidget(self.label_2)

        self.loginPassword = QtGui.QLineEdit(self.layoutWidget)
        self.loginPassword.setObjectName("loginPassword")
        self.loginPassword.setEchoMode(QtGui.QLineEdit.Password)
        self.hboxlayout1.addWidget(self.loginPassword)
        self.vboxlayout.addLayout(self.hboxlayout1)

        self.hboxlayout2 = QtGui.QHBoxLayout()
        self.hboxlayout2.setMargin(0)
        self.hboxlayout2.setSpacing(6)
        self.hboxlayout2.setObjectName("hboxlayout2")

        self.label_3 = QtGui.QLabel(self.layoutWidget)
        self.label_3.setObjectName("label_3")
        self.label_3.setFixedWidth(80)
        self.hboxlayout2.addWidget(self.label_3)

        self.label_http = QtGui.QLabel(self.layoutWidget)
        self.label_http.setObjectName("label_http")
        self.hboxlayout2.addWidget(self.label_http)

        self.loginDomain = QtGui.QLineEdit(self.layoutWidget)
        self.loginDomain.setObjectName("loginDomain")
        self.hboxlayout2.addWidget(self.loginDomain)
        self.vboxlayout.addLayout(self.hboxlayout2)

        self.hboxlayout3 = QtGui.QHBoxLayout()
        self.hboxlayout3.setMargin(0)
        self.hboxlayout3.setSpacing(6)
        self.hboxlayout3.setObjectName("hboxlayout3")

        self.hboxlayout4 = QtGui.QHBoxLayout()
        self.hboxlayout4.setMargin(0)
        self.hboxlayout4.setSpacing(6)
        self.hboxlayout4.setObjectName("hboxlayout4")

        self.label_4 = QtGui.QLabel(self.layoutWidget)
        self.label_4.setObjectName("label_4")
        self.label_4.setFixedWidth(80)
        self.hboxlayout4.addWidget(self.label_4)

        self.checkBox = QtGui.QCheckBox(self.layoutWidget)
        self.checkBox.setObjectName("checkBox")
        self.hboxlayout4.addWidget(self.checkBox)
        #self.hboxlayout3.addWidget(self.checkBox)
        #self.vboxlayout.addLayout(self.hboxlayout3)

        self.proxyServer = QtGui.QLineEdit(self.layoutWidget)
        self.proxyServer.setObjectName("proxyServer")
        self.hboxlayout4.addWidget(self.proxyServer)
        #self.hboxlayout3.addLayout(self.hboxlayout4)
        self.vboxlayout.addLayout(self.hboxlayout4)

        self.hboxlayout5 = QtGui.QHBoxLayout()
        self.hboxlayout5.setMargin(0)
        self.hboxlayout5.setSpacing(6)
        self.hboxlayout5.setObjectName("hboxlayout5")

        self.label_5 = QtGui.QLabel(self.layoutWidget)
        self.label_5.setObjectName("label_5")
        self.label_5.setFixedWidth(80)
        self.hboxlayout5.addWidget(self.label_5)

        self.comboBox = QtGui.QComboBox(self.layoutWidget)
        self.comboBox.setObjectName("comboBox")
        self.hboxlayout5.addWidget(self.comboBox)
        self.vboxlayout.addLayout(self.hboxlayout5)

        self.hboxlayout6 = QtGui.QHBoxLayout()
        self.hboxlayout6.setMargin(0)
        self.hboxlayout6.setSpacing(6)
        self.hboxlayout6.setObjectName("hboxlayout6")

        self.buttonLogin = QtGui.QPushButton(self.layoutWidget)
        self.buttonLogin.setObjectName("buttonLogin")
        self.hboxlayout6.addWidget(self.buttonLogin)

        self.buttonCancel = QtGui.QPushButton(self.layoutWidget)
        self.buttonCancel.setObjectName("buttonCancel")
        self.hboxlayout6.addWidget(self.buttonCancel)

        self.buttonDeleteCurrent = QtGui.QPushButton(self.layoutWidget)
        self.buttonDeleteCurrent.setObjectName("buttonDeleteCurrent")
        self.hboxlayout6.addWidget(self.buttonDeleteCurrent)
        self.vboxlayout.addLayout(self.hboxlayout6)
        self.label.setBuddy(self.loginName)
        self.label_2.setBuddy(self.loginPassword)
        self.label_3.setBuddy(self.loginDomain)
        self.label_4.setBuddy(self.proxyServer)
        self.label_5.setBuddy(self.comboBox)

        self.retranslateUi(Dialog)
        QtCore.QObject.connect(self.buttonCancel,QtCore.SIGNAL("clicked()"),Dialog.reject)
        QtCore.QMetaObject.connectSlotsByName(Dialog)

    def retranslateUi(self, Dialog):
        Dialog.setWindowTitle(QtGui.QApplication.translate("Dialog", "INGC Login", None, QtGui.QApplication.UnicodeUTF8))
        self.label.setText(QtGui.QApplication.translate("Dialog", "用户名: ", None, QtGui.QApplication.UnicodeUTF8))
        self.label_2.setText(QtGui.QApplication.translate("Dialog", "密码: ", None, QtGui.QApplication.UnicodeUTF8))
        self.label_3.setText(QtGui.QApplication.translate("Dialog", "Babel 域名: ", None, QtGui.QApplication.UnicodeUTF8))
        self.label_http.setText(QtGui.QApplication.translate("Dialog", "Http:// ", None, QtGui.QApplication.UnicodeUTF8))
        self.label_4.setText(QtGui.QApplication.translate("Dialog", "代理服务器: ", None, QtGui.QApplication.UnicodeUTF8))
        self.checkBox.setText(QtGui.QApplication.translate("Dialog", "启用", None, QtGui.QApplication.UnicodeUTF8))
        self.label_5.setText(QtGui.QApplication.translate("Dialog", "已储存账号: ", None, QtGui.QApplication.UnicodeUTF8))
        self.comboBox.addItem(QtGui.QApplication.translate("Dialog", "--当前未选择--", None, QtGui.QApplication.UnicodeUTF8))
        self.buttonLogin.setText(QtGui.QApplication.translate("Dialog", "登录", None, QtGui.QApplication.UnicodeUTF8))
        self.buttonCancel.setText(QtGui.QApplication.translate("Dialog", "取消", None, QtGui.QApplication.UnicodeUTF8))
        self.buttonDeleteCurrent.setText(QtGui.QApplication.translate("Dialog", "删除当前选择账户", None, QtGui.QApplication.UnicodeUTF8))

class loginDialog(QtGui.QDialog):
	def __init__(self, setting, parent = None):
		QtGui.QWidget.__init__(self, parent)
		self.setting = setting
		self.dialog = Ui_Dialog()
		self.dialog.setupUi(self)
		self.setStyleSheet('QLineEdit{border: 1px solid #666666; background: #eeeeee;}QLineEdit:focus{background: #FFFFFF;}')
		self.accounts = {}
		self.setting.beginGroup('Accounts')
		if self.setting.childGroups() != []:
			for i in self.setting.childGroups():
				if i != QString('MainWindow'):
					self.setting.beginGroup(i)
					t = []
					t.append(self.setting.value('username').toString())
					t.append(self.setting.value('password').toString())
					t.append(self.setting.value('domain').toString())
					t.append(self.setting.value('proxy').toString())
					t.append(self.setting.value('proxyEnabled').toString())
					self.accounts[i] = t
					self.dialog.comboBox.addItem(i)
					self.setting.endGroup()
		self.setting.endGroup()
		QtCore.QObject.connect(self.dialog.buttonLogin, QtCore.SIGNAL('clicked()'), self.doLogin)
		QtCore.QObject.connect(self.dialog.comboBox, QtCore.SIGNAL('activated(const QString&)'), self.comboxActivated)
		QtCore.QObject.connect(self.dialog.buttonDeleteCurrent, QtCore.SIGNAL('clicked()'), self.deleteCurrentItem)

	def deleteCurrentItem(self):
		if self.dialog.comboBox.currentText().contains('@'):
			group = self.dialog.comboBox.currentText()
			self.setting.beginGroup('Accounts')
			self.setting.beginGroup(group)
			self.setting.remove('')
			self.setting.endGroup()
			self.setting.endGroup()
			self.dialog.comboBox.removeItem(self.dialog.comboBox.currentIndex())
			self.dialog.loginName.setText('')
			self.dialog.loginPassword.setText('')
			self.dialog.loginDomain.setText('')
			self.dialog.proxyServer.setText('')
			self.dialog.checkBox.setCheckState(Qt.Unchecked)


	def comboxActivated(self, text):
		if text.contains('@'):
			selectedItem = self.accounts[text]
			self.dialog.loginName.setText(selectedItem[0])
			pwd = unicode(selectedItem[1].toUtf8())
			pwd = QString(base64.b64decode(pwd))
			self.dialog.loginPassword.setText(pwd)
			self.dialog.loginDomain.setText(selectedItem[2])
			self.dialog.proxyServer.setText(selectedItem[3])
			if selectedItem[4] == '2':
				self.dialog.checkBox.setCheckState(Qt.Checked)
		else:
			self.dialog.loginName.setText('')
			self.dialog.loginPassword.setText('')
			self.dialog.loginDomain.setText('')
			self.dialog.proxyServer.setText('')
			self.dialog.checkBox.setCheckState(Qt.Unchecked)

	def _restore(self):
		self.dialog.loginName.setStyleSheet('')
		self.dialog.loginPassword.setStyleSheet('')
		self.dialog.loginDomain.setStyleSheet('')
		self.dialog.proxyServer.setStyleSheet('')

	def doLogin(self):
		self.setStyleSheet('QLineEdit{border: 1px solid #666666; background: #eeeeee;}QLineEdit:focus{background: #FFFFFF;}')
		username = self.dialog.loginName.text().simplified()
		user_pwd = self.dialog.loginPassword.text().simplified()
		domain = self.dialog.loginDomain.text().simplified()
		if domain != '' and domain[-1] == '/':
			domain = domain[:-1]
		proxy = self.dialog.proxyServer.text().simplified()
		proxyEnabled = self.dialog.checkBox.checkState()
		if username == '':
			self._restore()
			self.dialog.loginName.setStyleSheet('QLineEdit{border: 1px solid #ff9166;}')
		elif user_pwd == '':
			self._restore()
			self.dialog.loginPassword.setStyleSheet('QLineEdit{border: 1px solid #ff9166;}')
		elif domain == '' or domain.startsWith('http', Qt.CaseInsensitive):
			self._restore()
			self.dialog.loginDomain.setStyleSheet('QLineEdit{border: 1px solid #ff9166;}')
		elif proxy != '' and proxy.indexOf(QRegExp('^\d+\.\d+\.\d+\.\d+\:\d+')) == -1:
			self._restore()
			self.dialog.proxyServer.setStyleSheet('QLineEdit{border: 1px solid #ff9166;}')
		else:
			self.hide()
			if proxy != '':
				p = 'http://' + proxy
			else:
				p = ''
			self.parent().addView('http://' + str(domain), str(username.toUtf8()).decode('utf-8', 'replace'), str(user_pwd), (self.dialog.checkBox.checkState() == Qt.Checked) and str(p) or '')
			self.parent().currentViewLogin()

			self.setting.beginGroup('accounts')
			#tempDomain = str(domain)
			#domain.remove('http://', Qt.CaseInsensitive)
			self.setting.beginGroup(username + '@' + domain)
			self.setting.setValue('username', QtCore.QVariant(username))
			pwd = unicode(user_pwd.toUtf8())
			pwd = QString(base64.b64encode(pwd))
			self.setting.setValue('password', QtCore.QVariant(pwd))
			self.setting.setValue('domain', QtCore.QVariant(domain))
			self.setting.setValue('proxy', QtCore.QVariant(proxy))
			self.setting.setValue('proxyEnabled', QtCore.QVariant(proxyEnabled))
			self.setting.endGroup()
			self.setting.endGroup()
			self.close()

